<template>
  <div id="pixi"></div>
</template>

<script>
import * as PIXI from "pixi.js";
import { onMounted } from "vue";
import { keyboard } from "./keyMeth";
export default {
  setup() {
    let type = "WebGL";
    const loader = PIXI.Loader.shared,
      resources = PIXI.Loader.shared.resources,
      TextureCache = PIXI.utils.TextureCache,
      Rectangle = PIXI.Rectangle,
      Sprite = PIXI.Sprite;

    if (!PIXI.utils.isWebGLSupported()) {
      type = "canvas";
    }
    PIXI.utils.sayHello(type);

    let app = new PIXI.Application({
      width: 1000,
      height: 500,
      antialias: true, // default: false 反锯齿
      backgroundAlpha: false, // default: false 透明度
      resolution: 1, // default: 1 分辨率
      backgroundColor: 0xffffff,
    });
    let rocket = null;
    let state = null;

    function init() {
      // 背景
      let bgSprite = new Sprite(resources[require("../assets/bg.png")].texture);
      bgSprite.width = 1000;
      bgSprite.height = 500;
      app.stage.addChild(bgSprite);

      // 扣雪碧图
      let texture = TextureCache[require("../assets/tileset.png")];
      // 拿到雪碧图的火箭
      let rectangle = new Rectangle(96, 64, 32, 32);
      texture.frame = rectangle;
      rocket = new Sprite(texture);

      rocket.vx = 0; // 设置 vx \ vy 的初始速度
      rocket.vy = 0;
      app.stage.addChild(rocket);
      app.renderer.render(app.stage);

      let left = keyboard("ArrowLeft"),
        up = keyboard("ArrowUp"),
        right = keyboard("ArrowRight"),
        down = keyboard("ArrowDown");
      // 绑定案件事件   press按下  release松手
      left.press = () => {
        rocket.vx = -5;
      };
      left.release = () => {
        rocket.vx = 0;
      };
      right.press = () => {
        rocket.vx = 5;
      };
      right.release = () => {
        rocket.vx = 0;
      };
      up.press = () => {
        rocket.vy = -5;
      };
      up.release = () => {
        rocket.vy = 0;
      };
      down.press = () => {
        rocket.vy = 5;
      };
      down.release = () => {
        rocket.vy = 0;
      };

      state = play;
      app.ticker.add((delta) => gameLoop(delta));
    }
    function gameLoop(delta) {
      // delta 是帧数 电脑卡就加上这个  不卡就不用
      // rocket.x += 1;  // 第一种 控制 x 大小运动

      // 第二种
      // rocket.vx = 1;
      // rocket.vy = 1;

      // rocket.x += rocket.vx;
      // rocket.y += rocket.vy;

      state(delta);
    }
    function play() {
      // rocket.vx = 1;
      // rocket.x += rocket.vx;

      rocket.x += rocket.vx;
      rocket.y += rocket.vy;
    }
    onMounted(() => {
      let box = document.getElementById("pixi");
      box.appendChild(app.view);
      loader
        .add(require("../assets/bg.png"))
        .add(require("../assets/role.gif"))
        .add(require("../assets/tileset.png"))
        .load(init);
    });
    return {};
  },
  components: {},
};
</script>

<style scoped lang="scss"></style>
